package com.clouddot.baipai.ui.fragment.V;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.clouddot.baipai.R;
import com.clouddot.baipai.component.DaggerIV_MainFragmentComponent;
import com.clouddot.baipai.contract.IMainFragmentContract;
import com.clouddot.baipai.http.entity.response.getArcticByIdResponse;
import com.clouddot.baipai.http.entity.response.getArcticListResponse;
import com.clouddot.baipai.http.entity.response.getClassInfoByIdResponse;
import com.clouddot.baipai.http.entity.response.getClassInfoListResponse;
import com.clouddot.baipai.http.entity.response.getCurrentCourseResponse;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.module.MainFragmentModule;
import com.clouddot.baipai.ui.Dialog.H_ContentDailog;
import com.clouddot.baipai.ui.activity.V_SMainActivity;
import com.clouddot.baipai.ui.adapter.V_MainNewsAdapter;
import com.clouddot.baipai.ui.adapter.V_MainImageAdapter;
import com.clouddot.baipai.util.EscapeUnescapeUtil;
import com.clouddot.baipai.util.ThreadPool.ThreadPoolFactory;
import com.clouddot.baipai.util.Toast.ToastUtil;
import com.clouddot.baipai.util.viewUtil.ViewAnim;

import org.wxy.sdk.base.IBasePresenter;
import org.wxy.sdk.base.impl.BaseFragment;
import org.wxy.sdk.util.imageloader.ImageLoaderUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_ONE;
import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_THREE;
import static com.clouddot.baipai.ui.activity.H_UMainActivity.MSG_TWO;
import static com.clouddot.baipai.util.viewUtil.ViewUtil.imageGetter;

/**
 * Created by wxy on 2018/8/23.
 * 横版班牌首页的主页面
 */

public class V_MainFrgment extends BaseFragment implements IMainFragmentContract.IView, ViewPager.OnPageChangeListener, View.OnTouchListener {
    private List<getClassInfoListResponse.classInfoItem> EntityList = new ArrayList<>();
    private List<getClassInfoListResponse.attachment> imgList = new ArrayList<>();
    private List<getArcticListResponse.ariticInfo> mDataList = new ArrayList<>();
    private V_MainNewsAdapter adapter;

    private int currentNoticeItem;
    private int currentPage = 1;
    private V_MainImageAdapter ImageAdapter;
    private List<ImageView> mItems;
    private ImageView[] mBottomImages;
    private boolean isLive = true;
    private int currentViewPagerItem = -1;
    private boolean isAutoPlay = true;

    private H_ContentDailog dailog;

    @Inject
    IMainFragmentContract.IPresenter mPresenter;

    @BindView(R.id.Viewpager)
    ViewPager Viewpager;
    @BindView(R.id.indicator)
    LinearLayout indicator;

    @BindView(R.id.topLoading)
    ImageView topLoading;
    @BindView(R.id.topLoadingP)
    RelativeLayout topLoadingP;
    @BindView(R.id.leftContent)
    ScrollView leftContent;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.tvcontent)
    TextView tvcontent;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.leftLoading)
    ImageView leftLoading;
    @BindView(R.id.leftLoadingP)
    RelativeLayout leftLoadingP;

    @BindView(R.id.rightLoading)
    ImageView rightLoading;
    @BindView(R.id.rightLoadingP)
    RelativeLayout rightLoadingP;
    @BindView(R.id.lession_name)
    TextView lession_name;
    @BindView(R.id.teacher_photo)
    ImageView teacher_photo;
    @BindView(R.id.teacher_name)
    TextView teacher_name;
    @BindView(R.id.teach_week)
    TextView teach_week;
    @BindView(R.id.teacher_time)
    TextView teacher_time;
    @BindView(R.id.teacher_info)
    LinearLayout teacher_info;


    @Override
    public IBasePresenter getPresenter() {
        return mPresenter;
    }

    @Override
    protected View inflateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState) {
        return inflater.inflate(R.layout.v_fragment_main, null);
    }

    @Override
    protected void initViews() {
        DaggerIV_MainFragmentComponent.builder().mainFragmentModule(new MainFragmentModule(this)).build().inject(this);

        ThreadPoolFactory.getThread().execute(new Runnable() {
            @Override
            public void run() {
                mPresenter.getClassInfo(1, "notice", Env.getAppContext().ClassID, 1, 10);
                mPresenter.getClassInfo(2, "image", Env.getAppContext().ClassID, 1, 10);
                mPresenter.getCurrentCourse(Env.getAppContext().ClassID);
                mPresenter.getArcticList("XXXW", 1, 8);
            }
        });

        Viewpager.setOnTouchListener(this);
        Viewpager.setOnPageChangeListener(this);
    }

    @Override
    protected void initVariables() {
        Animation loadingAnim = ViewAnim.getRotateImg(getActivity());
        topLoading.startAnimation(loadingAnim);
        leftLoading.startAnimation(loadingAnim);
        rightLoading.startAnimation(loadingAnim);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    @OnClick({
            R.id.notice_last, R.id.notice_next
    })
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.notice_last:
                if (currentNoticeItem == 0) {
                    ToastUtil.showToast(getActivity(), "没有上一条了");
                    return;
                }
                topLoadingP.setVisibility(View.VISIBLE);
                leftContent.setVisibility(View.GONE);
                mPresenter.getClassInfoById(EntityList.get(--currentNoticeItem).Id);
                break;
            case R.id.notice_next:
                if (EntityList.isEmpty()) return;
                if (currentNoticeItem >= EntityList.size() - 1) {
                    ToastUtil.showToast(getActivity(), "没有下一条了");
                    return;
                }
                topLoadingP.setVisibility(View.VISIBLE);
                leftContent.setVisibility(View.GONE);
                mPresenter.getClassInfoById(EntityList.get(++currentNoticeItem).Id);
                break;
        }
    }

    /**
     * fragment 隐藏和显现触发的方法，第一次生成的时候不会触发。
     *  hidden 为 false --> 显现 ；为 true --> 隐藏
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            isLive = true;
            leftContent.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            teacher_photo.setVisibility(View.GONE);
            lession_name.setVisibility(View.GONE);
            teacher_info.setVisibility(View.GONE);
            topLoadingP.setVisibility(View.VISIBLE);
            leftLoadingP.setVisibility(View.VISIBLE);
            rightLoadingP.setVisibility(View.VISIBLE);
            mDataList.clear();
            ThreadPoolFactory.getThread().execute(new Runnable() {
                @Override
                public void run() {
                    mPresenter.getClassInfo(1, "notice", Env.getAppContext().ClassID, 1, 10);
                    mPresenter.getClassInfo(2, "image", Env.getAppContext().ClassID, 1, 10);
                    mPresenter.getCurrentCourse(Env.getAppContext().ClassID);
                    mPresenter.getArcticList("XXXW", 1, 8);
                }
            });
        } else {
            isLive = false;
        }
    }

    @Override
    protected void loadData() {
    }

    /**
     *
     * @param flag 1 --> 获取班级通知的内容
     *             2 --> 获取班级通知和班级相册的列表
     *             3 --> 获取当前正在上课的课程
     *             4 --> 获取新闻的列表
     *             5 --> 获取新闻的详细内容
     * @param object
     */
    @Override
    public void success(int flag, Object object) {
        if (flag == 1) {
            refulesClassNoticeInfo(object);
        } else if (flag == 2) {
            refulesClassNoticeAndImage(object);
        } else if (flag == 3) {
            refulesCurrentCourse(object);
        } else if (flag == 4) {
            refulesNewsList(object);
        } else if (flag == 5) {
            refulesNewsItemInfo(object);
        }
    }

    private boolean flag = true;

    /**
     * 更新班级通知和班级图片数据
     * @param object
     */
    private void refulesClassNoticeAndImage(Object object) {
        getClassInfoListResponse response = (getClassInfoListResponse) object;
        if (response.flag == 1) {
            EntityList = response.EntityList;
            mPresenter.getClassInfoById(response.EntityList.get(0).Id);
            currentNoticeItem = 0;
        } else if (response.flag == 2) {
            imgList = response.EntityList.get(0).Attachments;
            ImageAdapter = new V_MainImageAdapter(addImageView(imgList), getActivity());
            Viewpager.setAdapter(ImageAdapter);
            if (!imgList.isEmpty()) {
                if (flag) {
                    flag = false;
                    ThreadPoolFactory.getThread().execute(startAutoPlay);
                    creatCriclePoint();
                }
            }
        }
    }

    /**
     * 更新班级通知的内容
     * @param object
     */
    private void refulesClassNoticeInfo(Object object) {
        getClassInfoByIdResponse response = (getClassInfoByIdResponse) object;
        title.setText(response.Title);
        time.setText(response.CreateTime);
        final String html = EscapeUnescapeUtil.unescape(response.Detail);
        ThreadPoolFactory.getThread().execute(new Runnable() {
            @Override
            public void run() {
                final Spanned sp = Html.fromHtml(html, imageGetter, null);
                Message message = new Message();
                message.what = MSG_ONE;
                message.obj = sp;
                handler.sendMessage(message);
            }
        });
        topLoadingP.setVisibility(View.GONE);
        leftContent.setVisibility(View.VISIBLE);
    }


    /**
     * 更新学校新闻列表数据
     * @param object
     */
    private void refulesNewsList(Object object) {
        getArcticListResponse response = (getArcticListResponse) object;
        if (response.EntityList.isEmpty()) {
            if (adapter != null) adapter.loadMoreEnd();
            return;
        }
        if (mDataList.isEmpty()) {
            mDataList = response.EntityList;
            adapter = new V_MainNewsAdapter(mDataList);
            adapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
                @Override
                public void onLoadMoreRequested() {
                    mPresenter.getArcticList("XXXW", ++currentPage, 8);
                }
            });
            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                    V_SMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                    mPresenter.getArcticById(mDataList.get(position).Id);
                }
            });
            recyclerView.setAdapter(adapter);
            recyclerView.setVisibility(View.VISIBLE);
            leftLoadingP.setVisibility(View.GONE);

        } else {
            adapter.addData(response.EntityList);
            adapter.loadMoreComplete();
        }

    }

    /**
     * 更新学校新闻某个item内容，dialog显示
     * @param object
     */
    private void refulesNewsItemInfo(Object object) {
        getArcticByIdResponse response = (getArcticByIdResponse) object;
        dailog = new H_ContentDailog(getActivity());
        dailog.getCloseView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                V_SMainActivity.backTime = Env.getAppContext().backToMainTime * 60;
                dailog.closeDialog();
            }
        });
        dailog.showDialog();
        dailog.getTextViews().get(0).setText(response.BaseData.Title);
        dailog.getTextViews().get(1).setText(response.BaseData.CreateTimeText);
        if (response.BaseData.Detail != null && !response.BaseData.Detail.isEmpty()) {
            final String html = EscapeUnescapeUtil.unescape(response.BaseData.Detail);
            ThreadPoolFactory.getThread().execute(new Runnable() {
                @Override
                public void run() {
                    final Spanned sp = Html.fromHtml(html, imageGetter, null);
                    Message message = new Message();
                    message.what = MSG_THREE;
                    message.obj = sp;
                    handler.sendMessage(message);
                }
            });
        }

    }

    /**
     * 获取班级正在上课课程
     * @param object
     */
    private void refulesCurrentCourse(Object object) {
        getCurrentCourseResponse response = (getCurrentCourseResponse) object;
        lession_name.setText("正在上课：" + response.CourseName);
        teacher_name.setText(response.TeacherName);
        teach_week.setText("星期 " + getWeekStr(response.WeekNo));
        teacher_time.setText("第 " + getWeekStr(response.ClassNo) + " 节");
        ImageLoaderUtil.getInstance().loadImage("http://" + Env.getAppContext().IP + "", teacher_photo);

        rightLoadingP.setVisibility(View.GONE);
        teacher_info.setVisibility(View.VISIBLE);
        teacher_photo.setVisibility(View.VISIBLE);
    }

    @Override
    public void fail(int flag, String errMsg) {
        if (flag == 1) {
            topLoadingP.setVisibility(View.GONE);
            leftContent.setVisibility(View.VISIBLE);
            title.setText(errMsg);
            time.setText("");
            tvcontent.setText("");
        } else if (flag == 3) {
            lession_name.setText(errMsg);
            lession_name.setVisibility(View.VISIBLE);
            rightLoadingP.setVisibility(View.GONE);
            teacher_info.setVisibility(View.GONE);
            teacher_photo.setVisibility(View.GONE);
        } else if (flag == 4) {
            leftLoadingP.setVisibility(View.GONE);
        }
        ToastUtil.showToast(getActivity(), errMsg);

    }

    /**
     * handle机制更新页面
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @SuppressLint("SetTextI18n")
        @Override
        public void handleMessage(final Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_ONE:
                    tvcontent.setText((Spanned) msg.obj);
                    break;

                case MSG_TWO:
                    if (isAutoPlay) {
                        ++currentViewPagerItem;
                        currentViewPagerItem = currentViewPagerItem % mItems.size();
                        if (Viewpager != null) Viewpager.setCurrentItem(currentViewPagerItem);
                    }
                    break;
                case MSG_THREE:
                    if (dailog != null) dailog.getTextViews().get(2).setText((Spanned) msg.obj);
                    break;
            }
        }
    };

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        currentViewPagerItem = position;
        if (!mItems.isEmpty()) {
            position %= mBottomImages.length;
            int total = mBottomImages.length;

            for (int i = 0; i < total; i++) {
                if (i == position) {
                    mBottomImages[i].setImageResource(R.drawable.indicator_select);
                } else {
                    mBottomImages[i].setImageResource(R.drawable.indicator_no_select);
                }
            }
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                isAutoPlay = false;
                break;
            case MotionEvent.ACTION_UP:
                isAutoPlay = true;
                break;
        }
        return false;
    }

    private Runnable startAutoPlay = new Runnable() {
        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (isLive) handler.sendEmptyMessage(MSG_TWO);
            }
        }
    };

    private List<ImageView> addImageView(List<getClassInfoListResponse.attachment> strings) {
        mItems = new ArrayList<>();
        if (!strings.isEmpty()) {

            int size = strings.size() >= 3 ? 3 : strings.size();
            for (int i = 0; i < size; i++) {
                ImageView view0 = new ImageView(getActivity());
                Glide.with(getActivity()).load("http://" + Env.getAppContext().IP + strings.get(i).RealPathName).asBitmap().centerCrop().placeholder(R.drawable.loadings).into(view0);
                mItems.add(view0);
            }
        } else {
            ToastUtil.showToast(getActivity(), "班级暂时没有图片");
        }
        return mItems;
    }

    private void creatCriclePoint() {
        mBottomImages = new ImageView[mItems.size()];
        for (int i = 0; i < mBottomImages.length; i++) {
            ImageView imageView = new ImageView(getActivity());
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(20, 20);
            params.setMargins(5, 0, 5, 0);
            imageView.setLayoutParams(params);
            //如果当前是第一个 设置为选中状态
            if (i == 0) {
                imageView.setImageResource(R.drawable.indicator_select);
            } else {
                imageView.setImageResource(R.drawable.indicator_no_select);
            }
            mBottomImages[i] = imageView;
            indicator.addView(imageView);
        }
    }

    private String getWeekStr(String str) {
        if (str.equals("1")) {
            return "一";
        } else if (str.equals("2")) {
            return "二";
        } else if (str.equals("3")) {
            return "三";
        } else if (str.equals("4")) {
            return "四";
        } else if (str.equals("5")) {
            return "五";
        } else if (str.equals("6")) {
            return "六";
        } else if (str.equals("7")) {
            return "七";
        } else if (str.equals("8")) {
            return "八";
        } else if (str.equals("9")) {
            return "九";
        } else if (str.equals("10")) {
            return "十";
        } else {
            return "未知";
        }

    }
}
